package javase.flyweight;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 享元工厂角色
 * 
 * @Package javase.flyweight
 * @ClassName: FlyweightFactory
 * @author Realfighter
 * @date 2014-8-4 下午04:49:30
 */
public class FlyweightFactory {

	// 使用同步的map集合，线程安全
	private Map<Object, Object> flyweights = Collections
			.synchronizedMap(new HashMap<Object, Object>());

	// 也可以使用hashtable
	//private HashTable<Object,Object> flyweights = new HashTable<Object,Object>();

	public FlyweightFactory() {
	}

	/**
	 * 获取享元对象
	 * 
	 * @Title: getFlyWeight
	 * @author Realfighter
	 * @date 2014-8-4 下午04:53:33
	 * @param obj
	 * @return Flyweight
	 */
	public Flyweight getFlyWeight(Object obj) {
		Flyweight flyweight = (Flyweight) flyweights.get(obj);
		if (flyweight == null) {
			// 产生新的ConcreteFlyweight
			flyweight = new ConcreteFlyweight((String) obj);
			flyweights.put(obj, flyweight);
		}
		return flyweight;
	}

	/**
	 * 获取享元对象的实际数量
	 * 
	 * @Title: getFlyweightSize
	 * @author Realfighter
	 * @date 2014-8-4 下午04:52:56
	 * @return int
	 */
	public int getFlyweightSize() {
		return flyweights.size();
	}

}
